package com.example.controller;


import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.vavr.control.Try;

import com.xinpai.ouroboros.data.model.DataModel;
import com.xinpai.ouroboros.data.record.RecordList;
import com.xinpai.ouroboros.logicflow.model.FlowModel;
import com.xinpai.ouroboros.logicflow.model.FlowModelCenter;
import com.xinpai.ouroboros.util.Maps;
import com.xinpai.ouroboros.web.PagedWebApiResult;

import com.xinpai.ouroboros.data.model.DataModelCenter;
import com.xinpai.ouroboros.web.WebApiResult;

@RestController
@RequestMapping("/master-table")
public class DemoController {
  final static Logger logger = LoggerFactory.getLogger(DemoController.class);
  @GetMapping("/get-all")
  public PagedWebApiResult<Map<String, Object>> getAll1() {
    DataModel dataModel = getDataModel();
    if (dataModel == null) {
      return PagedWebApiResult.error("No data model found");
    }

    long total = dataModel.count(Collections.emptyMap()).getOrElse(0L);
    RecordList items = dataModel.query(Collections.emptyMap())
        .getOrElse(RecordList::empty);
    return PagedWebApiResult.success(total, (List<Map<String, Object>>)(List) items);
  }

  @GetMapping("")
  public WebApiResult<Object> getAll2(@RequestParam Map<String, Object> params) {
    FlowModel flowModel = getSearchFlowModel();
    if (flowModel == null) {
      return WebApiResult.error("No search flow model found");
    }
    logger.info("params: {}", params);
    Map<String, Object> request = Collections.singletonMap("params", Maps.Nested.build(params));
    Try<Object> result = flowModel.execute(request);
    return WebApiResult.of(result);
  }

  private DataModel getDataModel() {
    return DataModelCenter.getDataModel("MasterTable").orElse(null);
  }

  private FlowModel getSearchFlowModel() {
    return FlowModelCenter.getFlowModel("MasterTable.search").orElse(null);
  }
}
